import sys
sys.path.append("..//")

import RadarCameraDetction.Radar as Radar
import cv2
import multiprocessing
import base64
import paho.mqtt.client as mqtt
import json
import RadarCameraDetction.utils.ObjectDection as od


# 消费者进程
def Getframe(q,mutex,empty,full):
    # 摄像头相关设置
    capture = cv2.VideoCapture(0)
    capture.set(3, 1280)  # width=1280
    capture.set(4, 720)  # height=720

    client = RigisteEMQ()

    while True:
        ret, frame = capture.read()
        frame = cv2.flip(frame, 1)  # 镜像操作

        full.acquire()
        mutex.acquire()
        # 消费一个数据
        radarTarget = q.get()
        mutex.release()
        empty.release()

        # 进行cv检测
        frame = od.ObjectDect(frame)
        # 加上雷达信息
        frame = TagOnPic(radarTarget,frame)

        ret, jpeg = cv2.imencode('.jpg', frame)

        # 图片转Base64编码
        base64pic = base64.b64encode(jpeg)
        radarTarget['picinfo'] = str(base64pic,encoding='utf-8')

        # 序列化json
        radarTagetstr = json.dumps(radarTarget)

        # 通过mqtt发布
        client.publish('R&C', payload=radarTagetstr, qos=0)
        print("published!")
        # 需要使用一个数据库存储frame信息

# 生产者进程
def GetRadarTaget(q,mutex,empty,full):
    Radar.init()
    ser, error = Radar.Open(9600)
    if ser == None:
        while True:
            empty.acquire()
            # 生产进程
            RadarTarget = {}
            mutex.acquire()
            # 放入缓冲区
            q.put(RadarTarget)
            mutex.release()
            full.release()
    else:
    # assert ser != None
        while True:
            empty.acquire()
            # 生产进程
            RadarTarget = Radar.GetData(ser)
            mutex.acquire()
            # 放入缓冲区
            q.put(RadarTarget)
            mutex.release()
            full.release()

def TagOnPic(radarTarget,frame):
    targetnum = radarTarget['RadarTagnum']
    if targetnum == 0:
        return frame
    for item in radarTarget['RadarTaglist']:
        distance = item['distance'] * 1.0 / 100
        posX = int(item['X'])
        posY = int(item['Y'])
        cv2.circle(frame, (posX, posY), 1, (0, 255, 0), 5)
        disstr = "distance = " + str(distance)
        cv2.putText(frame, disstr, (posX - 50, posY - 50), cv2.FONT_HERSHEY_PLAIN, 2, (0, 255, 0), 5)
    return frame

def RigisteEMQ():

    def on_connect(client, userdata, flags, rc):
        print("Connected with result code: " + str(rc))

    def on_message(client, userdata, msg):
        # print(msg.topic + " " + str(msg.payload))
        return

    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.username_pw_set("RadarAndCamera", "123")
    client.connect('192.168.56.101', 1883, 600)  # 600为keepalive的时间间隔

    return client

def Run():
    # 传递数据的队列 共享单元 默认一次传递一个大小 因此大小位1
    q = multiprocessing.Queue(1)

    # 进程互斥锁 同一时间只能由一个进程访问队列
    mutex = multiprocessing.Semaphore(1)
    # empty表示当前空闲容量 full表示使用容量
    empty = multiprocessing.Semaphore(1)
    full = multiprocessing.Semaphore(0)

    p1 = multiprocessing.Process(target=Getframe, args=(q,mutex,empty,full))
    p2 = multiprocessing.Process(target=GetRadarTaget, args=(q,mutex,empty,full))
    p1.start()
    p2.start()

if __name__ == '__main__':
    Run()






